/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ses;

import Entity.City;
import ses.exceptions.IllegalOrphanException;
import ses.exceptions.NonexistentEntityException;
import ses.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import Entity.Order1;
import java.util.ArrayList;
import java.util.List;
import Entity.AccountDetails;
import javax.transaction.UserTransaction;

/**
 *
 * @author Huu Vinh
 */
public class CityJpaController implements Serializable {

    public CityJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(City city) throws RollbackFailureException, Exception {
        if (city.getOrder1List() == null) {
            city.setOrder1List(new ArrayList<Order1>());
        }
        if (city.getAccountDetailsList() == null) {
            city.setAccountDetailsList(new ArrayList<AccountDetails>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<Order1> attachedOrder1List = new ArrayList<Order1>();
            for (Order1 order1ListOrder1ToAttach : city.getOrder1List()) {
                order1ListOrder1ToAttach = em.getReference(order1ListOrder1ToAttach.getClass(), order1ListOrder1ToAttach.getOrderId());
                attachedOrder1List.add(order1ListOrder1ToAttach);
            }
            city.setOrder1List(attachedOrder1List);
            List<AccountDetails> attachedAccountDetailsList = new ArrayList<AccountDetails>();
            for (AccountDetails accountDetailsListAccountDetailsToAttach : city.getAccountDetailsList()) {
                accountDetailsListAccountDetailsToAttach = em.getReference(accountDetailsListAccountDetailsToAttach.getClass(), accountDetailsListAccountDetailsToAttach.getAccId());
                attachedAccountDetailsList.add(accountDetailsListAccountDetailsToAttach);
            }
            city.setAccountDetailsList(attachedAccountDetailsList);
            em.persist(city);
            for (Order1 order1ListOrder1 : city.getOrder1List()) {
                City oldCityIdOfOrder1ListOrder1 = order1ListOrder1.getCityId();
                order1ListOrder1.setCityId(city);
                order1ListOrder1 = em.merge(order1ListOrder1);
                if (oldCityIdOfOrder1ListOrder1 != null) {
                    oldCityIdOfOrder1ListOrder1.getOrder1List().remove(order1ListOrder1);
                    oldCityIdOfOrder1ListOrder1 = em.merge(oldCityIdOfOrder1ListOrder1);
                }
            }
            for (AccountDetails accountDetailsListAccountDetails : city.getAccountDetailsList()) {
                City oldCityIdOfAccountDetailsListAccountDetails = accountDetailsListAccountDetails.getCityId();
                accountDetailsListAccountDetails.setCityId(city);
                accountDetailsListAccountDetails = em.merge(accountDetailsListAccountDetails);
                if (oldCityIdOfAccountDetailsListAccountDetails != null) {
                    oldCityIdOfAccountDetailsListAccountDetails.getAccountDetailsList().remove(accountDetailsListAccountDetails);
                    oldCityIdOfAccountDetailsListAccountDetails = em.merge(oldCityIdOfAccountDetailsListAccountDetails);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(City city) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            City persistentCity = em.find(City.class, city.getCityId());
            List<Order1> order1ListOld = persistentCity.getOrder1List();
            List<Order1> order1ListNew = city.getOrder1List();
            List<AccountDetails> accountDetailsListOld = persistentCity.getAccountDetailsList();
            List<AccountDetails> accountDetailsListNew = city.getAccountDetailsList();
            List<String> illegalOrphanMessages = null;
            for (Order1 order1ListOldOrder1 : order1ListOld) {
                if (!order1ListNew.contains(order1ListOldOrder1)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Order1 " + order1ListOldOrder1 + " since its cityId field is not nullable.");
                }
            }
            for (AccountDetails accountDetailsListOldAccountDetails : accountDetailsListOld) {
                if (!accountDetailsListNew.contains(accountDetailsListOldAccountDetails)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain AccountDetails " + accountDetailsListOldAccountDetails + " since its cityId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Order1> attachedOrder1ListNew = new ArrayList<Order1>();
            for (Order1 order1ListNewOrder1ToAttach : order1ListNew) {
                order1ListNewOrder1ToAttach = em.getReference(order1ListNewOrder1ToAttach.getClass(), order1ListNewOrder1ToAttach.getOrderId());
                attachedOrder1ListNew.add(order1ListNewOrder1ToAttach);
            }
            order1ListNew = attachedOrder1ListNew;
            city.setOrder1List(order1ListNew);
            List<AccountDetails> attachedAccountDetailsListNew = new ArrayList<AccountDetails>();
            for (AccountDetails accountDetailsListNewAccountDetailsToAttach : accountDetailsListNew) {
                accountDetailsListNewAccountDetailsToAttach = em.getReference(accountDetailsListNewAccountDetailsToAttach.getClass(), accountDetailsListNewAccountDetailsToAttach.getAccId());
                attachedAccountDetailsListNew.add(accountDetailsListNewAccountDetailsToAttach);
            }
            accountDetailsListNew = attachedAccountDetailsListNew;
            city.setAccountDetailsList(accountDetailsListNew);
            city = em.merge(city);
            for (Order1 order1ListNewOrder1 : order1ListNew) {
                if (!order1ListOld.contains(order1ListNewOrder1)) {
                    City oldCityIdOfOrder1ListNewOrder1 = order1ListNewOrder1.getCityId();
                    order1ListNewOrder1.setCityId(city);
                    order1ListNewOrder1 = em.merge(order1ListNewOrder1);
                    if (oldCityIdOfOrder1ListNewOrder1 != null && !oldCityIdOfOrder1ListNewOrder1.equals(city)) {
                        oldCityIdOfOrder1ListNewOrder1.getOrder1List().remove(order1ListNewOrder1);
                        oldCityIdOfOrder1ListNewOrder1 = em.merge(oldCityIdOfOrder1ListNewOrder1);
                    }
                }
            }
            for (AccountDetails accountDetailsListNewAccountDetails : accountDetailsListNew) {
                if (!accountDetailsListOld.contains(accountDetailsListNewAccountDetails)) {
                    City oldCityIdOfAccountDetailsListNewAccountDetails = accountDetailsListNewAccountDetails.getCityId();
                    accountDetailsListNewAccountDetails.setCityId(city);
                    accountDetailsListNewAccountDetails = em.merge(accountDetailsListNewAccountDetails);
                    if (oldCityIdOfAccountDetailsListNewAccountDetails != null && !oldCityIdOfAccountDetailsListNewAccountDetails.equals(city)) {
                        oldCityIdOfAccountDetailsListNewAccountDetails.getAccountDetailsList().remove(accountDetailsListNewAccountDetails);
                        oldCityIdOfAccountDetailsListNewAccountDetails = em.merge(oldCityIdOfAccountDetailsListNewAccountDetails);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = city.getCityId();
                if (findCity(id) == null) {
                    throw new NonexistentEntityException("The city with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            City city;
            try {
                city = em.getReference(City.class, id);
                city.getCityId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The city with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Order1> order1ListOrphanCheck = city.getOrder1List();
            for (Order1 order1ListOrphanCheckOrder1 : order1ListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This City (" + city + ") cannot be destroyed since the Order1 " + order1ListOrphanCheckOrder1 + " in its order1List field has a non-nullable cityId field.");
            }
            List<AccountDetails> accountDetailsListOrphanCheck = city.getAccountDetailsList();
            for (AccountDetails accountDetailsListOrphanCheckAccountDetails : accountDetailsListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This City (" + city + ") cannot be destroyed since the AccountDetails " + accountDetailsListOrphanCheckAccountDetails + " in its accountDetailsList field has a non-nullable cityId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(city);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<City> findCityEntities() {
        return findCityEntities(true, -1, -1);
    }

    public List<City> findCityEntities(int maxResults, int firstResult) {
        return findCityEntities(false, maxResults, firstResult);
    }

    private List<City> findCityEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from City as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public City findCity(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(City.class, id);
        } finally {
            em.close();
        }
    }

    public int getCityCount() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from City as o");
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
